package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.bean.User;
import com.db.DBUtil;

public class UserDao {
	
	DBUtil dbUtil = new DBUtil();

    /**
     * 保存用户
     * @param user
     */
    public void saveUser(User user){

        String sql="insert into users(username,password,sex,age,qq) values" +
                "('"+user.getUsername()+"','"+user.getPassword()+"',"
                		+"'"+user.getSex()+"',"+ "'"+user.getAge()+"',"+"'"+user.getQq()+"'"+")";
        try {
            dbUtil.insertOrUpdate(sql);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            dbUtil.close();
        }
    }

    /**
     * 验证用户是否已经存在
     * @param qq
     * @return
     */
    public boolean valideIsExist(String qq){
        String sql="select count(1) as num from  users where qq='"+qq+"'";
        long num =0;
        try {
            ResultSet result=dbUtil.query(sql);
            while (result.next()){
            	num= result.getLong("num");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            dbUtil.close();
        }
        return num>0?true:false;
    }

    /**
     * 查找用户
      * @param qq
     * @return
     */
    public User findOne(String qq){
        String sql="select * from  users where qq='"+qq+"'";
        User c = new User();
        try {
            ResultSet result=dbUtil.query(sql);
            while (result.next()){

                c.setId(result.getInt("id"));
                c.setUsername(result.getString("username"));
                c.setPassword(result.getString("password"));
                c.setAge(result.getString("age"));
                c.setHeadPic(result.getString("headpic"));
                c.setSex(result.getString("sex"));
                c.setQq(result.getString("qq"));

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            dbUtil.close();
        }
        return c;
    }

}
